import type { RequestOptions } from '@/interceptors/request'
import { useAuthorization } from '@/composables/app'
import { Toast } from './toast'

export function createApi<T = any>(options: RequestOptions) {
  const { errorMsg = false, loading = false } = options
  if (loading) {
    uni.showLoading({
      title: '加载中',
    })
  }
  return new Promise<T>((resolve, reject) => {
    uni.request({
      ...options,
      dataType: 'json',
      // #ifdef MP-WEIXIN
      responseType: 'json',
      // #endif
      success: (result) => {
        const { statusCode } = result
        const data = (result.data || {}) as Result
        const { success, message, code } = data
        // 无权限 statusCode是网络错误码 code是业务错误码 可以根据自己项目的错误码来判断
        if ([401, 403].includes(statusCode) || [401, 403].includes(code)) {
          const token = useAuthorization()
          // 无权限
          token.value = ''
          Toast.error('登录已失效，请重新登录')
          reject(data)
          return
        }

        // 其他错误
        if ((statusCode >= 200 && statusCode < 300) || !success) {
          if (errorMsg) {
            Toast.error(message || '请求失败，请稍后再试')
          }
          reject(data)
          return
        }

        resolve(data as T)
      },
      fail: (error) => {
        Toast.error('网络错误，请稍后再试')
        reject(error)
      },
      complete: () => {
        if (loading) {
          uni.hideLoading()
        }
      },
    })
  })
}

export const Http = {
  get: <T = any>(url: string, params?: any, options?: RequestOptions) => createApi<Result<T>>({ url, method: 'GET', data: params, ...options }),
  post: <T = any>(url: string, data?: any, options?: RequestOptions) => createApi<Result<T>>({ url, method: 'POST', data, ...options }),
  put: <T = any>(url: string, data?: any, options?: RequestOptions) => createApi<Result<T>>({ url, method: 'PUT', data, ...options }),
  delete: <T = any>(url: string, data?: any, options?: RequestOptions) => createApi<Result<T>>({ url, method: 'DELETE', data, ...options }),
}
